package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
	"weibo-sys/cache"
	"weibo-sys/models"
)

func WeiboList(c *gin.Context) {
	key := c.Query("key")
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size
	var weibo []models.Weibo
	redis_key := "weibo_list_page_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("title like ?", "%"+key+"%").
			Offset(offset).Limit(size).Debug().Find(&weibo)
		jsonData, _ := json.Marshal(weibo)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &weibo)
	}
	var total int64
	models.DB.Model(&models.Weibo{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  weibo,
		"total": total,
	})
}

func WeiboDetail(c *gin.Context) {
	id := c.PostForm("id")
	var weibo models.Weibo
	redis_key := "weibo_detail_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id = ?", id).Debug().Find(&weibo)
		jsonData, _ := json.Marshal(weibo)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &weibo)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": weibo,
	})
}
